#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cassert>
using namespace std;

pid_t child_pid;
int status = 0;

void handler(int signo)
{
    // 收到SIGCHLD信号，子进程必定已经退出，等待回收子进程
    cout << "wait child process success!!" << endl;
    waitpid(child_pid, &status, 0);

    cout << "exit code: " << ((status >> 8) & 0xff) << endl;
    cout << "signal: " << (status & 0x7f) << endl;
}

int main()
{
    signal(SIGCHLD, handler);
    // signal(SIGCHLD, SIG_IGN);
    pid_t id = fork();
    assert(id >= 0);

    child_pid = id;
    if (id == 0)
    {
        int cnt = 5;
        while (cnt--)
        {
            cout << "child process is running..." << endl;
            sleep(1);
        }
        exit(2);
    }

    while (true)
    {
        cout << "parent process is do something..." << endl;
        sleep(1);
    }

    return 0;
}